package com.asynccommand.framework;

import java.util.ArrayList;
import java.util.Map;

public class CommandsController {

	public enum State {
		STATE_INPROGRESS, STATE_DONE, STATE_ERROR
	}

	private static CommandsController instance;

	private ArrayList<ICommandListener> listeners;

	private CommandsController() {
		listeners = new ArrayList<ICommandListener>();
	}

	public static CommandsController get() {
		if (instance == null) {
			instance = new CommandsController();
		}
		return instance;
	}

	/**
	 * Registra los listeners de los commands.
	 * 
	 * @param listener
	 */
	public void register(ICommandListener listener) {
		this.listeners.add(listener);
	}

	/**
	 * Elimina el listener de los commands
	 * 
	 * @param listener
	 */
	public void unregister(ICommandListener listener) {
		this.listeners.remove(listener);
	}

	/**
	 * Recibe el cambio de estado de los commands y dispara los listeners.
	 * 
	 * @param actionID
	 * @param state
	 * @param params
	 */
	void changeRequestState(int actionID, State state,
			Map<String, Object> params) {
		for (ICommandListener listener : listeners) {
			switch (state) {
			case STATE_DONE:
				listener.onDone(actionID, params);
				break;

			case STATE_INPROGRESS:
				listener.onProgress(actionID, params);
				break;

			case STATE_ERROR:
				listener.onError(actionID, params);
				break;

			default:
				break;
			}
		}
	}

}
